package com.example.baseapp.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.baseapp.admin.entity.RoleMenu;
import com.example.baseapp.admin.mapper.RoleMenuMapper;
import com.example.baseapp.admin.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * RoleMenuServiceImpl class
 *
 * @author zhangl
 * @date 2022/4/29 11:59
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Resource
    protected RoleMenuMapper roleMenuMapper;
    @Override
    public List<RoleMenu> getRoleMenuByMenuId(String menuId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<RoleMenu>()
                .eq(StringUtils.hasText(menuId), RoleMenu::getMenuId,menuId);
        return roleMenuMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<RoleMenu> getRoleMenuByRoleId(String roleId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<RoleMenu>()
                .eq(StringUtils.hasText(roleId), RoleMenu::getRoleId,roleId);
        return roleMenuMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<String> getRoleIdByMenuId(String menuId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<RoleMenu>()
                .eq(RoleMenu::getMenuId,menuId)
                .groupBy(RoleMenu::getRoleId);
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(lambdaQueryWrapper);
        return roleMenuList.stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
    }

    @Override
    public boolean insert(RoleMenu roleMenu) {

        return roleMenuMapper.insert(roleMenu) > 0;
    }

    @Override
    public boolean insert(List<RoleMenu> roleMenuList) {
        int i = 0 ;
        for (RoleMenu roleMenu : roleMenuList){
           i += roleMenuMapper.insert(roleMenu);
        }
        return roleMenuList.size() == i;
    }

    @Override
    public boolean update(RoleMenu roleMenu) {
        LambdaUpdateWrapper<RoleMenu> lambdaUpdateWrapper = new LambdaUpdateWrapper<RoleMenu>()
                .eq(StringUtils.hasText(roleMenu.getMenuId()), RoleMenu::getMenuId, roleMenu.getMenuId())
                .eq(StringUtils.hasText(roleMenu.getMenuId()), RoleMenu::getRoleId, roleMenu.getRoleId());
        return roleMenuMapper.updateById(roleMenu) > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        return roleMenuMapper.deleteById(new RoleMenu().setId(id)) == 1;
    }

    @Override
    public boolean delete(String menuId) {

        return roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId,menuId)) != 0;
    }

}
